package exploit

import (
	"fmt"
	"github.com/cdk-team/CDK/pkg/cli"
	"github.com/cdk-team/CDK/pkg/plugin"
	"github.com/cdk-team/CDK/pkg/util"
	"log"
	"os"
	"strings"
)

// APIs Ref https://github.com/AbsoZed/DockerPwn.py/blob/master/createContainer.py
// curl --unix-socket /var/run/docker.sock http://127.0.0.1/info
func CheckDockerSock(path string) {
	_, err := os.Stat(path)
	if err != nil {
		log.Fatal("Errs found when stat docker.sock:", err)
	}
	body := util.UnixHttpSend("get", path, "http://127.0.0.1/info", "")
	fmt.Println("\t" + body)
	if strings.Contains(body, "Containers") {
		log.Println("success, docker.sock is available. please use `./cdk ucurl` commands to control docker API")
		log.Println("you can find Docker APIs in https://docs.docker.com/engine/api/v1.24/")
		log.Println("happy escaping!")
	} else {
		log.Fatal("cannot get docker daemon info from target unix socket.")
	}
}

// plugin interface
type DINDAttackS struct{}

func (p DINDAttackS) Desc() string {
	return "check if docker unix socket available. usage: ./cdk docker-sock-check <sock_path>"
}
func (p DINDAttackS) Run() bool {
	args := cli.Args["<args>"].([]string)
	if len(args) != 1 {
		log.Println("invalid input args.")
		log.Fatal(p.Desc())
	}
	sock := args[0]
	log.Println("checking docker socket: ", sock)
	CheckDockerSock(sock)
	return true
}

func init() {
	exploit := DINDAttackS{}
	plugin.RegisterExploit("docker-sock-check", exploit)
}
